package pl.olsson.plugin;

import java.io.File;
import java.io.FileReader;
import java.util.List;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import org.apache.maven.plugin.AbstractMojo;
import org.codehaus.plexus.util.FileUtils;
import pl.olsson.plugin.script.Context;
import pl.olsson.plugin.script.ProxyWriter;

/**
 * @author nilols
 * @goal run
 * @phase generate-sources
 * @execute phase="process-resources"
 */
public class RunMojo extends AbstractMojo {

    /**
     * @parameter default-value="${basedir}/src/main/resources"
     */
    private String path;

    /**
     * @parameter expression="${project.build.directory}"
     * @readonly
     */
    private String buildDirectory;

    /**
     * @parameter
     * @required
     */
    private List<String> types;

    @Override
    public void execute() {
        ScriptEngineManager manager = new ScriptEngineManager();
        for (String type: types) {
            ScriptEngine engine = manager.getEngineByName(type);
            engine.setContext(new Context(new File(buildDirectory)));
            String[] extensions = getExtensions(engine);
            for (String name: FileUtils.getFilesFromExtension(path, extensions)) {
                try {
                    getLog().info("Script::Run: "+name);
                    engine.eval(new FileReader(new File(name)));
                    engine.getContext().getWriter().flush();
                    engine.getContext().getWriter().close();
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }

    private String[] getExtensions(ScriptEngine engine) {
        List<String> extensions = engine.getFactory().getExtensions();
        getLog().info("Script::Extensions: "+extensions);
        return extensions.toArray(new String[extensions.size()]);
    }

    public void setPath(String path) {
        this.path = path;
        getLog().info("Script::Path: "+path);
    }

    public void setTypes(List<String> types) {
        this.types = types;
        getLog().info("Script::Types: "+types);
    }

    public void setBuildDirectory(String buildDirectory) {
        this.buildDirectory = buildDirectory;
        getLog().info("Script::Output: "+buildDirectory);
    }
}
